package com.xunsiya.service.module.order.impl;

import com.xunsiya.common.config.RequestUtils;
import com.xunsiya.common.config.util.ConstantInfo;
import com.xunsiya.common.config.util.DateUtil;
import com.xunsiya.module.order.dao.OrderDetailMapper;
import com.xunsiya.module.order.dao.OrderMapper;
import com.xunsiya.module.order.dao.ProductMapper;
import com.xunsiya.module.order.dao.ProductPriceMapper;
import com.xunsiya.module.order.vo.*;
import com.xunsiya.service.module.order.OrderService;
import com.xunsiya.system.dao.CompanyMapper;
import com.xunsiya.system.vo.Company;
import com.xunsiya.system.vo.User;
import com.xunsiya.tools.common.msg.Msg;
import com.xunsiya.tools.common.pagination.ForePage;
import com.xunsiya.tools.common.pagination.PagedUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (填写类功能描述)
 *
 * @author panjun
 * @version 1.0
 *          <p>
 *          <p>修订人		修订时间			描述信息
 *          <p>-----------------------------------------------------
 *          <p>panjun		2018/10/31		初始创建
 */
@Service("orderService")
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    ProductPriceMapper productPriceMapper;

    @Autowired
    CompanyMapper companyMapper;

    /**
     * 查询用户订单
     *
     * @param userId 用户编号
     * @return
     */
    @Override
    public List<Order> findByUserId(Integer userId) {
        return orderMapper.findByUserId(userId);
    }

    /**
     * 查询订单详情
     *
     * @param ids 订单编号
     * @return
     */
    @Override
    public List<OrderDetail> findOrderDetailsByOrderIds(List<Long> ids) {
        return orderDetailMapper.findOrderDetailsByOrderIds(ids);
    }

    /**
     * 添加订单
     *
     * @param orderDto 订单对象
     * @return
     */
    @Override
    public boolean save(OrderDto orderDto) {
        // 当前用户
        User user = RequestUtils.getSessionAttribte(User.SYS_LOGIN_INFO);
        Order order = new Order();
        OrderDetail orderDetail = new OrderDetail();
        // 产品编号
        Long[] ids = orderDto.getProductIds();
        boolean bool = false;
        for (Long id : ids) {
            Product product = productMapper.findOne(id);
            //新订单业务处理
            if (StringUtils.isNotBlank(orderDto.getEmail())) {
                order.setEmail(orderDto.getEmail().trim());
            }

            if (StringUtils.isNotBlank(orderDto.getMobile())) {
                order.setMobile(orderDto.getMobile().trim());
            }

            if (StringUtils.isNotBlank(orderDto.getUserName())) {
                order.setUserName(orderDto.getUserName().trim());
            }

            if (StringUtils.isNotBlank(orderDto.getImgUrl())) {
                order.setImgUrl(orderDto.getImgUrl().trim());
            }
            // 保存订单
            order.setOrderStatus(0);
            order.prePersist(user.getId() + "");
            order.setId(genId());
            order.setCompanyId(orderDto.getCompanyId());
            //初始化租用月份
            Integer num = null;
            // 人脸识别
            if (id == ConstantInfo.ProductType.FACE_REC.getValue()) {
                order.setImgUrl("0");
                num = orderDto.getFaceMonNum();
            } // 图像识别
            else if (id == ConstantInfo.ProductType.IMG_REC.getValue()) {
                order.setImgUrl("1");
                num = orderDto.getImgMonNum();
            } else { // 视频会议
                order.setImgUrl("2");
                num = orderDto.getMeetingMonNum();
            }
            orderDetail.setProductService(num + "个月租借方案");
            orderMapper.save(order);

            //根据产品编号和月份查询产品价格信息
            ProductPrice productPrice = productPriceMapper.queryByProductIdAndMon(product.getId().intValue(), num);
            //订单详情
            orderDetail.setProductId(productPrice.getId().longValue());

            if (StringUtils.isNotBlank(product.getProductName())) {
                orderDetail.setProductName(product.getProductName());
            }
            // 查询存在的订单
            OrderDetail orderDetail1 = orderDetailMapper.findByProductId(productPrice.getId().longValue(), orderDto.getCompanyId());
            ZonedDateTime zonedDateTime = ZonedDateTime.now();
            // 如果上次购买时间大于现在的时间，在上次的时间上延期
            if (orderDetail1 != null && orderDetail1.getOutDate().after(new Date())) {
                zonedDateTime = ZonedDateTime.ofInstant(orderDetail1.getOutDate().toInstant(), ZoneId.systemDefault());
            }

            if (productPrice.getMonNum() != null && productPrice.getMonNum() > 0) {
                ZonedDateTime outDate = zonedDateTime.plus(productPrice.getMonNum(), ChronoUnit.MONTHS);
                orderDetail.setProductPrice(product.getProductPrice());
                orderDetail.setOutDate(Date.from(outDate.toInstant()));
            }
            // 保存订单详情
            orderDetail.setOrderId(order.getId());
            orderDetail.setId(genId());
            orderDetail.prePersist(user.getId() + "");
            bool = orderDetailMapper.save(orderDetail);
        }
        return bool;
    }

    /**
     * 添加订单详情
     *
     * @param orderDetail 订单详情
     * @return
     */
    @Override
    public boolean saveOrderDetail(OrderDetail orderDetail) {
        return orderDetailMapper.save(orderDetail);
    }

    /**
     * 查询公司订单
     *
     * @param companyIds 公司编号
     * @return
     */
    @Override
    public List<Order> findByCompanyId(List<Integer> companyIds, int pageIndex, Integer pageSize) {
        List<Order> orderList = orderMapper.findByCompanyId(companyIds, 0, pageSize);
        return orderList;
    }

    /**
     * 生产id yyyyMMdd+时间戳+随机数（3）
     *
     * @return
     */
    private Long genId() {
        // 时间
        Date date = new Date();
        String dateStr = DateUtil.formatDate(date, "yyyy");
        // 随机数
        int random = (int) ((Math.random() + 1) * 10);
        return new Long(dateStr + date.getTime() + random);
    }

    /**
     * 查询存在的订单详情
     *
     * @param companyId 公司编号
     * @param parentId  产品父编号
     * @return
     */
    @Override
    public OrderDetail findByCompanyIdAndParentId(Integer companyId, Integer parentId) {
        //根据公司编号查询公司信息
        Company company = companyMapper.findParentId(companyId);
        List<Integer> companyIds = new ArrayList<>();
        companyIds.add(companyId);

        Integer pId = company.getParentId();

        // 如果不是母公司
        while (pId != 0) {
            company = companyMapper.findParentId(pId);
            companyIds.add(pId);
            pId = company.getParentId();
        }
        return orderDetailMapper.findByCompanyIdAndParentId(companyIds, parentId);
    }

    /**
     * 分页查询订单
     *
     * @param company   公司
     * @param pageIndex 开始页
     * @param pageSize  每页大小
     * @return
     */
    @Override
    public Msg queryForPage(Company company, Integer pageIndex, Integer pageSize) {
        //查询数量
        int count = orderDetailMapper.queryCount(company);
        List<OrderDetail> list = new ArrayList<>();
        try {
            if (count > 0) {
                list = orderDetailMapper.queryForPage(company, PagedUtil.getStartIndex(pageIndex, pageSize), pageSize);
                list.forEach(od -> od.setOrderIdStr(od.getOrderId() + ""));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ForePage fp = new ForePage<>(count, pageIndex, list);
        return new Msg(true, "", fp);
    }
}
